package service

import (
	"oa-system/internal/api/request"
	"oa-system/internal/model"
	"oa-system/internal/repository"
	"oa-system/pkg/errors"
)

type DictionaryService interface {
	GetDictionariesByType(dictType string) ([]model.Dictionary, error)
	CreateDictionary(req *request.CreateDictionaryRequest) (*model.Dictionary, error)
	UpdateDictionary(id uint, req *request.UpdateDictionaryRequest) (*model.Dictionary, error)
	DeleteDictionary(id uint) error
	GetDictionaryByID(id uint) (*model.Dictionary, error)
	GetAllDictionaries(page, pageSize int, typeSearch, labelSearch string) ([]model.Dictionary, int64, error)
	GetDictionaryByTypeAndValue(dictType, value string) (*model.Dictionary, error)
}

type dictionaryService struct {
	repo repository.DictionaryRepository
}

func NewDictionaryService(repo repository.DictionaryRepository) DictionaryService {
	return &dictionaryService{repo: repo}
}

func (s *dictionaryService) GetDictionariesByType(dictType string) ([]model.Dictionary, error) {
	return s.repo.GetDictionariesByType(dictType)
}

func (s *dictionaryService) CreateDictionary(req *request.CreateDictionaryRequest) (*model.Dictionary, error) {
	dict := &model.Dictionary{
		Type:        req.Type,
		Label:       req.Label,
		Value:       req.Value,
		Sort:        req.Sort,
		Description: req.Description,
	}
	return s.repo.CreateDictionary(dict)
}

func (s *dictionaryService) UpdateDictionary(id uint, req *request.UpdateDictionaryRequest) (*model.Dictionary, error) {
	dict, err := s.repo.GetDictionaryByID(id)
	if err != nil {
		return nil, errors.NewNotFoundError("字典不存在", err)
	}

	dict.Type = req.Type
	dict.Label = req.Label
	dict.Value = req.Value
	dict.Sort = req.Sort
	dict.Description = req.Description

	return s.repo.UpdateDictionary(dict)
}

func (s *dictionaryService) DeleteDictionary(id uint) error {
	if _, err := s.repo.GetDictionaryByID(id); err != nil {
		return errors.NewNotFoundError("字典不存在", err)
	}
	return s.repo.DeleteDictionary(id)
}

func (s *dictionaryService) GetDictionaryByID(id uint) (*model.Dictionary, error) {
	return s.repo.GetDictionaryByID(id)
}

func (s *dictionaryService) GetAllDictionaries(page, pageSize int, typeSearch, labelSearch string) ([]model.Dictionary, int64, error) {
	return s.repo.GetAllDictionaries(page, pageSize, typeSearch, labelSearch)
}

func (s *dictionaryService) GetDictionaryByTypeAndValue(dictType, value string) (*model.Dictionary, error) {
	return s.repo.GetDictionaryByTypeAndValue(dictType, value)
}
